'use strict';
var entityCollection = require('./EntityCollection');

var relation = {
};

//添加引用关系
//entityName: 被引用实体名
//refEntityName: 引用实体名
//refField: 引用字段
exports.addReference = function(entityName, refEntityName, refField){
	if (!relation.hasOwnProperty(entityName)){
		relation[entityName] = {};
	}
	if (!relation[entityName].hasOwnProperty(refEntityName)){
		relation[entityName][refEntityName] = [];
	}

	relation[entityName][refEntityName].push(refField);
};

//entityName： 实体名称
//condition：删除条件
exports.deleteVerify = function(entityName, condition, resultHandel){
	if (relation.hasOwnProperty(entityName)) {
		var self = this;
		var entity = entityCollection.getEntity(entityName);
		entity.find(condition, null, null, function(err, deleteRecords){
			if(err){
				resultHandel(err);
			}
			else{
				if(deleteRecords.length == 0){
					resultHandel();
				}
				else{
					var errors = [];
					var references = [];	//被引用的实体记录

					var ids = [];
					for(var i=0; i<deleteRecords.length; i++){
						ids.push(deleteRecords[i]._id);
					}
					var refEntityNameCount = 0;

					var promises = [];
					for(var refEntityName in relation[entityName]){
						refEntityNameCount++;

						var condition = {$or: []};
				        for(var j=0; j<relation[entityName][refEntityName].length; j++){
				            var filedCondition = {};
				            filedCondition[relation[entityName][refEntityName][j]] = {$in: ids};
				            condition['$or'].push(filedCondition);
				        }

				        promises.push(new Promise(function(resolve, reject) {
                            var refEntity = entityCollection.getEntity(refEntityName);
					        refEntity.findOne(condition, null, function(err, refRecord){
					        	if(err){
									reject(err);
								}
								else{
									if(refRecord != null){
										resolve({EntityName: refEntity.EntityName, Record: refRecord});
									}
									else{
										resolve();
									}
								}
					        });
				        }));
					}

					Promise.all(promises).then(function(datas){
						var refDatas = [];
						datas.forEach(function (data) {
							if(data){
		  		        		refDatas.push(data);
	  		        		}   
						});
						if(refDatas.length == 0){
							resultHandel();
						}
						else{
							resultHandel({
								level: 5,
								title: '删除失败',
								message: entity.Name + " 被 " + entityCollection.getEntity(refDatas[0].EntityName).Name + " 引用，不能删除"
							});
						}
					}).catch(function(err){
						resultHandel(err);
					});
				}
			}
		});
	}
	else{
		resultHandel();
	}
};
